﻿<%@ Application Language="C#" %>
<%@ Import Namespace="m.avis.cn" %>

<script runat="server">

    // 维护旧地址跳转，英文逗号分隔多个地址-
    string[] oldpath = "/promotionaldetails.html".Split(',');
    string[] newpath = "/promotion.aspx".Split(',');

    void Application_Start(object sender, EventArgs e)
    {
        //异步获取identityserver 的token
         CallIdentityServer.GetTokenAsync().GetAwaiter();
      
      
    }

    void Application_BeginRequest(object sender, EventArgs e)
    {
        string path = Request.Path.ToLower().Replace("/mc/", "/").Replace("/m/", "/");
        string query = Request.Url.Query;

        if(path=="/mc" || path=="/m") {
            Response.Redirect(path+"/");
            return;
        }
        if(path=="/cmbm/" || path=="/airchina/") {
            Response.Redirect(path.TrimEnd('/'));
            return;
        }
        path = path.TrimEnd('/');
/*
        string oldp = RewriteOldPath(path);
        if(oldp!=""){
            Context.RewritePath(oldp, "", query);
            return;
        }*/
        if (path.Contains(".") || path.Contains("/dist")) return;

        if(path.Contains("/cmbm") || path.Contains("/airchina")){
            path = "";
        }else{
            path = GetNewPath(path, ref query);
        }
        
        if (string.IsNullOrEmpty(path)) {
            path = "/default.aspx";
        }

        Context.RewritePath(path, "", query);

    }
    static Regex reg3 = new Regex(@"^(/\w+)(/[\w\-]+)?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    
    private string GetNewPath(string path, ref string query) {

        var match = reg3.Match(path);
        if (!match.Success) return string.Empty;

        string id = match.Groups[3].Value;
        if (!string.IsNullOrEmpty(id)) {
            if (!string.IsNullOrEmpty(query)) query += "&id=" + id.Substring(1);
            else query += "?id=" + id.Substring(1);
        }
        if (!string.IsNullOrEmpty(query)) query = query.Substring(1);

        return match.Groups[1].Value + match.Groups[2].Value + ".aspx";
    }
    private string RewriteOldPath(string path){
        for(int i=0;i<oldpath.Length;i++){
            if(oldpath[i]==path){
                return newpath[i];
            }
        }
        return "";
    }
</script>
